
/**
 * copyright(c) 2013 www.jiongshibaoliao.com, All Rights Reserved.
 * project: jiongshibaoliao 
 * author: 曾帅
 * date: 2014-1-9 上午11:00:01
 * version: v1.0
 */

package com.jiongshibaoliao.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiongshibaoliao.model.bean.UserBean;

/**
 * @project jiongshibaoliao
 * @author 曾帅 
 * @version 1.0
 * @date 2014-1-9 上午11:00:01   
 */

public class LoginFilter implements Filter {

	
	/**
	 * 
	 * @author 曾帅
	 * @version 1.0
	 * @date 2014-1-9 上午11:09:55
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		
	}

	
	/**
	 * 
	 * @author 曾帅
	 * @version 1.0
	 * @date 2014-1-9 上午11:09:55
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		UserBean userBean = (UserBean) req.getSession().getAttribute(UserBean.USER_SESSION_KEY);
		
		if (userBean == null) {
			Enumeration<?> enu = request.getParameterNames();
			Map<String, String> requestPramsMap = new HashMap<String, String>();
			while (enu.hasMoreElements()) {
				String paraName = String.valueOf(enu.nextElement());
				requestPramsMap.put(paraName, request.getParameter(paraName));
			}
			req.getSession().setAttribute("requestURI", req.getRequestURI().replace("/" + req.getContextPath(), ""));
			req.getSession().setAttribute("requestPramsMap", requestPramsMap);
			
			resp.sendRedirect("/login");
			return;
		} else {
			chain.doFilter(request, response);
		}
	}

	
	/**
	 * 
	 * @author 曾帅
	 * @version 1.0
	 * @date 2014-1-9 上午11:09:55
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

}
